<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Services\Admin\MenuService;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    /**
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login(Request $request): \Illuminate\Http\JsonResponse
    {
        $params = $this->validate($request, [
            'account' => 'required|string|min:4|max:20',
            'password' => 'required|string|min:6|max:20',
            'captcha.code' => 'required|string|size:5',
            'captcha.key' => 'required|string|size:60'
        ]);
        return success(data: User::login($params));
    }

    public function logout(): \Illuminate\Http\JsonResponse
    {
        User::disableCache();
        return success();
    }

    public function getUser(MenuService $menuService): \Illuminate\Http\JsonResponse
    {
        $user = User::user();
        $menu = User::isAdmin() ? $menuService->tree() : $menuService->getCacheTreeByRoles(array_column($user['roles'], 'id'));
        return success(data: ['userInfo' => User::user(), 'menus' => $menu]);
    }
}
